package FreqCtrl

import (
	"errors"
	"strconv"

	"github.com/garyburd/redigo/redis"
)

var conn redis.Conn

func Init(redisIp string, redisPort string) error {
	if redisIp == "" || redisPort == "" {
		return errors.New("The argument of the Init() is nil")
	}
	var err error
	conn, err = redis.Dial(redisIp, redisPort)
	return err
}

func ReleaseCon() {
	if conn != nil {
		conn.Close()
	}
}

func GetUserFreq(userId string) (map[string]int, error) {
	if conn == nil {
		return nil, errors.New("the server disconnect")
	}
	if userId == "" {
		return nil, errors.New("The argument of the GetUserFreq() is error")
	}
	var infomap map[string]int
	infomap = make(map[string]int)
	serr := conn.Send("HGETALL", userId)
	if serr != nil {
		return nil, serr
	}
	ferr := conn.Flush()
	if ferr != nil {
		return nil, ferr
	}
	params, err := redis.Strings(conn.Receive())
	for i := 0; i < len(params); i += 2 {
		count, err := strconv.Atoi(params[i+1])
		if err != nil {
			return nil, err
		}
		infomap[params[i]] = count
	}
	return infomap, err
}

func SetUserFreq(userId string, offerId string, count string) (int, error) {
	if conn == nil {
		return 0, errors.New("the server disconnect")
	}
	if userId == "" || offerId == "" || count == "" {
		return 0, errors.New("The argument of the SetUserFreq() is error")
	}
	err := conn.Send("HINCRBY", userId, offerId, count)
	if err != nil {
		return 0, err
	}
	ferr := conn.Flush()
	if ferr != nil {
		return 0, ferr
	}
	num, rerr := redis.Int(conn.Receive())
	if rerr != nil {
		return 0, rerr
	}
	return num, nil
}
